<template>
  <div class="dashboard-container">
    <h2 style="text-align: center">{{ infoTitle }}</h2>
    <el-steps
      :active="active"
      finish-status="success"
      align-center
      process-status="wait"
      style="margin-bottom: 40px"
    >
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="提交审核"></el-step>
    </el-steps>

    <el-form label-width="120px" :model="courseInfo">
      <!--  -->
      <el-form-item label="课程名称" style="width: 16%">
        <el-input
          v-model="courseInfo.course.title"
          placeholder="示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"
        ></el-input>
      </el-form-item>

      <el-form-item label="课程类别" style="width: 16%">
        <el-cascader
          v-model="subjectIds"
          :options="subjectList"
          @change="handleChange"
        ></el-cascader>
      </el-form-item>

      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.course.teacherId" placeholder="请选择">
          <el-option
            v-for="item in teacher"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="总课时数">
        <el-input
          placeholder="实例 16:25:30"
          style="width: 203px"
          v-model="courseInfo.course.lessonNum"
          controls-position="right"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <quill-editor
          ref="quill"
          v-model="courseInfo.des"
          :options="editorOption"
          style="height: 300px; width: 1200px"
        />
        <input type="file" @change="change" id="upload" style="display: none" />
      </el-form-item>
      <br /><br /><br />
      <!-- 图片上传 -->
      <el-form-item label="頭像">
        <el-upload
          action="http://localhost:8080//eduservice/teacher/uploadAvatar"
          list-type="picture-card"
          :on-success="uploadAvatar"
          :on-remove="handleRemove"
          :on-preview="handlePictureCardPreview"
          :file-list="fileList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="teacher.cover" />
        </el-dialog>
      </el-form-item>

      <!--价格标签  -->
      <el-form-item label="课程价格">
        <el-input
          placeholder="实例:10.00"
          style="width: 203px"
          v-model="courseInfo.course.price"
          @blur="priceHandle"
          controls-position="right"
        ></el-input>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
import subjectApi from "@/api/subject";
import teacherApi from "@/api/teacher";
import courseApi from "@/api/course";
// 富文本导入
// import { uploadImage } from "@/api/course"; //上传接口
import { quillEditor, Quill } from "vue-quill-editor";
import { container, ImageExtend } from "quill-image-extend-module";
Quill.register("modules/ImageExtend", ImageExtend);
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      // 上传文件
      fileList: [],
      dialogVisible: false,
      //进度条
      infoTitle: "发布新课程",
      active: 1,

      value: [],
      courseInfo: {
        course: {
          id: "",
          title: "",
          teacherId: "",
          subjectId: "",
          subjectParentId: "",
          price: "",
          lessonNum: "",
          cover: "",
        },
        des: "",
      },
      //查出来的教师列表
      teacher: [],
      teacherId: 0,
      //类别
      subjectList: [],
      subjectIds: [],
      // 富文本框参数设置
      editorOption: {
        modules: {
          ImageExtend: {
            loading: true, // 可选参数 是否显示上传进度和提示语
            name: "img", // 图片参数名
            size: 3, // 可选参数 图片大小，单位为M，1M = 1024kb
            action: courseApi.uploadImage, // 服务器地址, 如果action为空，则采用base64插入图片
            // response 为一个函数用来获取服务器返回的具体图片地址
            // 例如服务器返回{code: 200; data:{ url: 'xxx.com'}}
            // 则 return res.data.url
            response: (res) => {
              return data.url;
            },
            headers: (xhr) => {}, // 可选参数 设置请求头部
            start: () => {}, // 可选参数 自定义开始上传触发事件
            end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
            error: () => {}, // 可选参数 自定义网络错误触发的事件
            change: (xhr, formData) => {}, // 可选参数 选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
          },
          toolbar: {
            container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector("#upload").click(); // 劫持原来的图片点击按钮事件
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
    };
  },
  created() {
    this.init();
  },
  watch: {
    $route(to, from) {
      this.init();
    },
  },
  methods: {
    init() {
      //判断url地址上面有没有参数
      if (this.$route.params && this.$route.params.id) {
        this.courseInfo.id = this.$route.params.id;
        this.infoTitle = "修改课程";
        this.getCourseBack(this.courseInfo.id);
      } else {
        //添加课程页面url地址上面没有参数所以不会走if
        this.courseInfo = {
          course: {
            id: "",
            title: "",
            teacherId: "",
            subjectId: "",
            subjectParentId: "",
            price: "",
            lessonNum: "",
            cover: "",
          },
          des: "",
        };
        this.fileList = [];
      }
      this.getSubjectList();
      this.getTeacherList();
    },
    next() {
      if (this.$route.params && this.$route.params.id) {
        this.update()
      } else {
        this.save();
      }
    },
    handleChange(value) {
      this.courseInfo.course.subjectId = value[1];
      this.courseInfo.course.subjectParentId = value[0];
    },
    getSubjectList() {
      subjectApi
        .getSubjectList()
        .then((res) => {
          this.subjectList = res.data.subjectList;
        })
        .catch((err) => {});
    },
    getTeacherList() {
      teacherApi
        .getTeacherList()
        .then((res) => {
          this.teacher = res.data.teacher;
        })
        .catch((err) => {});
    },
    // 富文本支持图片
    change(e) {
      let file = e.target.files[0];
      const formData = new FormData();
      formData.append("file", file);
      courseApi.uploadImage(formData)
        .then((res) => {
          let quill = this.$refs.quill.quill;
          if (res.code == 200) {
            let length = quill.getSelection().index; //光标位置
            // 插入图片  图片地址
            quill.insertEmbed(length, "image", res.data.imagePath);
            // 调整光标到最后
            quill.setSelection(length + 1); //光标后移一位
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 上传头像的方法
    handleRemove(file, fileList) {
      this.dialogVisible = false;
      this.courseInfo.course.cover = "";
    },
    uploadAvatar(res, file, fileList) {
      this.courseInfo.course.cover = res.data.imagePath;
    },
    handlePictureCardPreview(file) {
      this.dialogVisible = true;
    },
    //监听价格输入框,保证2位小数精度
    priceHandle() {
      if (this.courseInfo.course.price.indexOf(".") == -1) {
        this.courseInfo.course.price = this.courseInfo.course.price + ".00";
      } else {
        let s = this.courseInfo.course.price.split(".");
        if (s[1].length == 1) {
          this.courseInfo.course.price = this.courseInfo.course.price + "0";
        }
      }
    },
    // 解决回显 价格没有小数点问题
    toFixed(num) {
      return (Math.round(num * 100) / 100).toFixed(2);
    },
    //新增course
    save() {
      courseApi
        .addCourseInfo(this.courseInfo)
        .then((res) => {
          this.$message({
            type: "success",
            message: "添加课程成功!",
          });
          this.$router.push({
            path: "/course/addChapter/" + res.data.courseId,
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "添加课程失败!",
          });
        });
    },
    //修改方法
    update() {
      courseApi
        .updateCourse(this.courseInfo)
        .then((res) => {
          this.$message({
            type: "success",
            message: "修改课程成功!",
          });
          this.$router.push({
            path: "/course/addChapter/" + res.data.courseId,
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "添加课程失败!",
          });
        });
    },
    // 查询回显数据
    getCourseBack(id) {
      courseApi
        .findCourseInfo(id)
        .then((res) => {
          let courseInfoBack = res.data.courseInfo;
          //把id放到参数里面,修改要用
          this.courseInfo.course.id = id;
          //回显富文本
          this.courseInfo.des = courseInfoBack.des;
          // 回显头像
          this.courseInfo.course.cover = courseInfoBack.course.cover;
          this.fileList = [{ name: "xxx", url: courseInfoBack.course.cover }];
          // 回显姓名
          this.courseInfo.course.title = courseInfoBack.course.title;
          // 回显课程类别
          this.subjectIds = [
            courseInfoBack.course.subjectParentId,
            courseInfoBack.course.subjectId,
          ];
          this.courseInfo.course.subjectParentId = this.subjectIds[0];
          this.courseInfo.course.subjectId = this.subjectIds[1];
          // 回显讲师
          this.courseInfo.course.teacherId = courseInfoBack.course.teacherId;
          // 回显课时数
          this.courseInfo.course.lessonNum = courseInfoBack.course.lessonNum;
          // 回显价格
          this.courseInfo.course.price = this.toFixed(
            courseInfoBack.course.price
          );
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "查询课程失败!",
          });
        });
    },
  },
};
</script>

<style >
</style>